package com.cangmaomao.m_mePen.fragment

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.ViewGroup
import com.cangmaomao.lib.action.f_mainFragment
import com.cangmaomao.lib.action.f_regFragment
import com.cangmaomao.lib.base.BaseFragment
import com.cangmaomao.lib.event.AppEvent
import com.cangmaomao.lib.utils.FileUtils.createFiles
import com.cangmaomao.lib.utils.SPUtil.create
import com.cangmaomao.lib.utils.toast
import com.cangmaomao.m_mePen.R
import com.cangmaomao.m_mePen.contract.LoginContract
import com.cangmaomao.m_mePen.presenter.LoginPresenter
import com.cangmaomao.network.request.HttpManage
import kotlinx.android.synthetic.main.f_login.*
import org.greenrobot.eventbus.EventBus

/**
 * 登陆
 */
class LoginFragment : BaseFragment<LoginContract.Presenter>(), LoginContract.View {

    override val contentViewLayoutID: Int
        get() = R.layout.f_login

    override fun context(): Context = _mActivity

    override fun layoutView(): ViewGroup = constraintLayout

    override fun initView(savedInstanceState: Bundle?) {
        LoginPresenter(this)
        bt_login.setOnClickListener { _ ->
            try {
                mRxPermissions!!.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe({
                            if (it.granted) {
                                p.start()
                            } else if (it.shouldShowRequestPermissionRationale) {
                                toast("请务必开启权限,功能才能正常使用!")
                            } else {
                                toast("请务必开启权限,功能才能正常使用!")
                            }
                        }, {
                            toast("请务必开启权限,功能才能正常使用!")
                        })
            } catch (e: Exception) {
                toast(e.message!!)
            }
        }
        tv_reg.setOnClickListener { EventBus.getDefault().post(AppEvent(f_regFragment, null)) }
    }

    override fun responseData(flag: Boolean, msg: String) {
        create("User").add("isLogin", flag).add("account", mobile())
        if (flag) {
            createFiles(mobile())
        }
        if (flag) EventBus.getDefault().post(AppEvent(f_mainFragment, null)) else toast(msg)
    }

    override fun requestFail(it: Throwable) {
        HttpManage.getInstance().loadingEnd()
        toast(it.message!!)
    }

    override fun mobile(): String {
        val acc = account.text.toString()
        if (!TextUtils.isEmpty(acc)) return acc else throw Exception("账号不能为空!")
    }

    override fun password(): String {
        val pwd = pwd.text.toString()
        if (!TextUtils.isEmpty(pwd)) return pwd else throw Exception("密码不能为空!")
    }

    override fun loadMap(): Map<String, String> {
        return mapOf("mobile" to mobile(), "password" to password())
    }

    override fun onRightClick() {
    }
}